<template>
  <a-card :bordered="false" class="card-area">
    <div class="table-page-search-wrapper">
      <a-form layout="vertical">
        <a-row :gutter="48">
          <a-col :md="8" :sm="12">
            <a-form-item label="所属院系">
              <a-select allowClear :disabled="selectMenu.college && selectMenu.college.length === 1"  v-model="queryParam.lsdwh" showSearch :filterOption="filterOption">
                <a-select-option  v-for="i in selectMenu.college" :key="i.id" :value="i.dwh">{{ i.dwh }} {{ i.dwmc }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12">
            <a-form-item label="专业号">
              <a-input v-model="queryParam.zyh" placeholder=""/>
              <!-- <a-select allowClear v-model="queryParam.zyh" showSearch :filterOption="filterOption">
                <a-select-option v-for="i in selectMenu.zyList" :key="i.id" :value="i.zyh">{{ i.zyh}} {{ i.zymc }}</a-select-option>
              </a-select> -->
            </a-form-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="8" :sm="12">
              <a-form-item label="专业名称">
                <a-input v-model="queryParam.zymc" placeholder=""/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="12">
              <a-form-item label="拼音简码">
                <a-input v-model="queryParam.pyjm" style="width: 100%"/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-checkbox @change="checkboxChange($event,'sssfbz')">本年度硕士招生</a-checkbox>
              <a-checkbox @change="checkboxChange($event,'bssfbz')">本年度博士招生</a-checkbox>
            </a-col>
          </template>
          <a-col :md="12" :sm="24">
            <span class="table-page-search-submitButtons" >
              <a-button type="primary"  @click="$refs.table.refresh(true)">查询</a-button>
              <a-button type="primary" v-hasPermission="'zyxx:add'" @click="openAdd">添加</a-button>
              <a-button type="primary" @click="exportExcel">导出</a-button>
              <a-button type="primary" v-hasPermission="'zyxx:delete'" @click="batchDelete">批量删除</a-button>
              <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
              <a @click="advanced = !advanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <major-edit
      ref="majorEdit"
      :visible.sync="visible"
      :editId.sync="editId"
      :selectMenu.sync="selectMenu"
      @cancel="visible = false"
      @create="handleCreate"
    />
    <s-table
      v-if="initDone"
      ref="table"
      size="default"
      rowKey="id"
      :columns="columns"
      :data="loadData"
      :alert="options.alert"
      :scroll="{x:1200}"
      :rowSelection="options.rowSelection">

      <span slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>

      <a slot="operation" slot-scope="a,b" v-hasPermission="'zyxx:update'" @click="openEdit(b)">修改</a>
    </s-table>
  </a-card>
</template>

<script>
import { STable } from '~'
import majorEdit from './majorEdit'

export default {
  name: 'TableList',
  components: {
    STable,
    majorEdit
  },
  data () {
    return {
      // 高级搜索 展开/关闭
      advanced: true,
      visible: false,
      editId: null,
      // 查询参数
      queryParam: {},
      // 表头
      columns: [
        {
          title: '序号',
          scopedSlots: { customRender: 'serial' },
          width:'6%',
        },
        {
          title: '学科专业码',
          width:'10%',
          dataIndex: 'xkzym'
        },
        {
          title: '专业名称',
          width:'15%',
          dataIndex: 'zymc'
        },
        {
          title: '所属院系',
          width:'15%',
          dataIndex: 'lsdwmc'
        },
        {
          title: '国际学科类别',
          width:'12%',
          dataIndex: 'gjxklbmc'
        },
        {
          title: '一级学科',
          width:'13%',
          dataIndex: 'yjxkmc'
        },
        // {
        //   title: '二级学科',
        //   dataIndex: 'dwjp'
        // },
        {
          title: '学位',
          width:'19%',
          dataIndex: 'sshbsxwmc'
        },
        {
          title: '培养模式',
          width:'10%',
          dataIndex: 'pymsmc'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.$nextTick(() => {
          this.selectedRowKeys = []
          this.$refs.table.clearSelected()
        })
        parameter.pageNum = parameter.pageNo
        let params = Object.assign(this.queryParam, parameter)
        return this.$api.base.majorList(params).then(res => {
          return {
            data: res.data.rows,
            pageNo: parameter.pageNum,
            pageSize: parameter.pageSize,
            totalPage: Math.ceil(res.data.total / parameter.pageSize),
            totalCount: res.data.total
          }
        })
      },
      selectedRowKeys: [],
      selectedRows: [],

      // custom table alert & rowSelection
      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: true, // 是否显示alert，已选中
      confirmLoading: false,
      selectMenu: {},
      initDone: false
    }
  },
  created () {
    this.initSelectMenu()
  },
  methods: {
    initSelectMenu () {
      let allRequest = [
        this.$api.base.subjectAll({
          xklb: '01'
        }),
        this.$api.base.collegeAll(),
        this.$api.base.dictionaryData('TYPE0347'),
        this.$api.base.dictionaryData('TYPE0023')
      ]
      Promise.all(allRequest).then(res => {
        this.selectMenu = {
          subject: res[0].data, // 学科信息
          college: res[1].data, // 院系信息
          pyms: res[2].data, // 培养模式
          xw: res[3].data // 学位
        }
        // this.queryParam.lsdwh = this.selectMenu.college[0].dwh
        this.$set(this.queryParam, 'lsdwh', this.selectMenu.college[0].dwh)
        this.initDone = true
      })
    },
    filterOption (value, op) {
      return op.componentOptions.children[0].text.indexOf(value) !== -1
    },
    yxChange (code) {
      this.$set(this.queryParam, 'zyh', '')
      if (code) {
        this.$api.base.majorAll({lsdwh: code}).then(res => {
          this.$set(this.selectMenu, 'zyList', res.data)
        })
      } else {
        this.$set(this.selectMenu, 'zyList', [])
      }
    },
    handleCreate () {
      const form = this.$refs.majorEdit.form
      form.validateFields((err, values) => {
        if (err) {
          return
        }
        for (const key in values) {
          if (['ejxkbssysj', 'yjxkbssysj', 'ejxksssysj', 'yjxksssysj'].includes(key) && values[key]) {
            values[key] = values[key].format('YYYY-MM-DD')
            console.log(values[key])
          }
        }
        values.sssfbz = values.sssfbz ? 1 : 0
        values.bssfbz = values.bssfbz ? 1 : 0
        if (values.ejxkm) {
          values.xkjbm = 2
        } else if (values.yjxkm && !values.ejxkm) {
          values.xkjbm = 1
        } else {
          delete values.xkjbm
        }
        if (this.editId) {
          this.$api.base.majorUpdate(Object.assign({id: this.editId}, values)).then(res => {
            this.$message.success('修改成功')
            this.$refs.table.refresh(false)
          })
        } else {
          this.$api.base.majorAdd(values).then((res) => {
            this.$message.success('添加成功')
            this.$refs.table.refresh(false)
          })
        }
        form.resetFields()
        this.visible = false
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    openAdd () {
      this.editId = null
      this.visible = true
      this.$refs.majorEdit.form.resetFields()
      this.$refs.majorEdit.yjSubject = []
    },
    openEdit (major) {
      this.visible = true
      this.$nextTick(() => {
        this.$changeDate(major)
        this.$refs.majorEdit.form.resetFields()
        this.$refs.majorEdit.form.setFieldsValue({lsdwh: major.lsdwh})
        this.$refs.majorEdit.pymsChange(major.pymsm)
        this.$refs.majorEdit.subjectChange(major.gjxklbm)
        // this.$refs.majorEdit.form.setFieldsValue(major)
        let sshbsxw = major.sshbsxw.split(',')
        // sshbsxw.length = sshbsxw.length - 1
        this.$refs.majorEdit.form.setFieldsValue(Object.assign({}, major, {sssfbz: +major.sssfbz === 1, bssfbz: +major.bssfbz === 1, sshbsxw}))
        this.editId = major.id
      })
    },
    batchDelete () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要专业信息')
        return
      }
      this.$confirm({
        title: '确定删除所选中的专业信息?',
        content: '当您点击确定按钮后，这些记录将会被彻底删除',
        centered: true,
        onOk: () => {
          let majorIds = []
          this.selectedRows.forEach(major => {
            majorIds.push(major.id)
          })
          this.$api.base.majorDelete(majorIds.join(',')).then(() => {
            this.$message.success('删除成功')
            this.selectedRowKeys = []
            this.selectedRows = []
            this.$refs.table.refresh(false)
            this.$refs.table.clearSelected()
          })
        },
        onCancel: () => {
        }
      })
      console.log(this.selectedRowKeys)
      console.log(this.selectedRows)
    },
    checkboxChange (e, key) {
      this.queryParam[key] = e.target.checked ? 1 : 0
    },
    exportExcel(){
      this.$export('base/zyxx/exportList',this.queryParam)
    }
  }
}
</script>
